home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 12320 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1020 b 

  1. From: RNorman@msn.com (Richard Norman)
  2. Subject: RE: Is This Bad Coding Practice?
  3. Date: 30 Mar 96 15:53:28 -0800
  4. References: <4jgnt2$9d1@loki.tor.hookup.net>
  5. Message-ID: <00001a80+00008b78@msn.com>
  6. Path: news.msn.com!msn.com
  7. Newsgroups: comp.lang.c
  8. Organization: The Microsoft Network (msn.com)
  9.  
  10. R Singh asks:
  11. >char *func1(void)
  12. >   {
  13. >   char test[100];
  14. >
  15. >   sprintf(test, "Test:  %d", 1);
  16. >   return test;
  17. >   }
  18. >
  19.  
  20. You don't ask if it usually works, but rather if it "bad" coding.
  21. Definitely.  Once func1 returns, the array test no longer exists,
  22. so that your pointer is invalid.
  23.  
  24. Your specific example uses the result immediately before anyone else 
  25. gets a chance to contaminate the stack, which is probably where the 
  26. array was stored.  However, next week you will forget, and move
  27. part of your code into one function, the other part into another.
  28. Then, next month, you will be using a multitasking system where 
  29. other threads have intervened between the function call and the
  30. use of the return value.
  31.  
  32. Don't do it!
  33.